<template>
	<view class="auth">
		<view class="info">
			<!-- <view class="line">
				<view class="l">同城分类：</view>
				<input type="text" class="r" placeholder="请选择分类" v-model="cate" />
				<u-icon size="20" color="#DCDCDC" style="margin-left: 10rpx;" name="arrow-down-fill"></u-icon>
				<uni-data-picker class="picker" :localdata="items" popup-title="请选择分类" @change="onchange"
					@nodeclick="onnodeclick"></uni-data-picker>
			</view> -->

			<view class="line">
				<view class="l">任务标题：</view>
				<input type="text" class="r" v-model="name" placeholder="请输入任务标题" />
			</view>
			<view class="line">
				<view class="l">所需人数：</view>
				<input type="number" class="r" v-model="num" placeholder="请输入所需人数" />
			</view>

			<!-- <view class="line">
				<view class="l">任务单价：</view>
				<input type="number" class="r" v-model="price" placeholder="请输入任务单价" />
			</view>
			<view class="line">
				<view class="l">上门时间：</view>
				<input type="text" class="r" disabled @click="show = true" v-model="time" />
				<u-icon size="20" color="#DCDCDC" style="margin-left: 10rpx;" name="arrow-down-fill"></u-icon>
			</view> -->
			<view class="line imgBox">
				<view class="l">任务内容：</view>
				<textarea v-model="content" class="r" placeholder="请输入任务内容" />
			</view>
			<view class="line imgBox">
				<view class="l">详细地址：</view>
				<textarea :value="locations.province+ locations.city + locations.district + locations.address" disabled
					class="r con" placeholder="请选择详细地址" @click="nearby" />
				<image src="../../../static/index/address.png" class="address" mode="" @click="nearby"></image>
			</view>
			<view class="line imgBox">
				<view class="l">任务图片：</view>
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="10"></u-upload>
			</view>
			<view class="line">
				<view class="l">联系人：</view>
				<input type="text" class="r" v-model="username" placeholder="请输入联系人" />
			</view>
			<view class="line">
				<view class="l">联系电话：</view>
				<input type="number" class="r" v-model="mobile" placeholder="请输入联系电话" />
			</view>
			<view class="voice">
				<view class="voicebtn" @click="play">
					<image src="../../../static/index/stop.png" v-if="stop" mode="" class="icon"></image>
					<image src="../../../static/index/doing.png" v-else mode="" class="icon"></image>
					<view class="word">录音</view>
				</view>
				<view class="shape" v-if="voicePath">
					<image src="../../../static/voice.png" class="icon" mode="" @click="playVoice"></image>
					<image src="../../../static/close.png" class="close" mode="" @click="voicePath = ''"></image>
				</view>
			</view>


		</view>
		<view class="agree">
			<view class="circle" @click="select = !select">
				<u-icon name="checkbox-mark" color="#FF8007" v-if="select"></u-icon>
			</view>
			<view class="other">我已阅读、理解并同意</view>
			<view class="rule" @click="article(5,'同城任务发布规则')">《同城任务发布规则》</view>
		</view>
		<view class="notice">温馨提示</view>
		<view class="notice" v-html="info"></view>
		<view class="btn" @click="save">发布</view>
		<!-- <u-datetime-picker :show="show" v-model="starttime" mode="datetime" @cancel="show = false" @close="show = false"
			@confirm="confirm"></u-datetime-picker> -->
		<u-calendar :show="show" @confirm="confirm" :maxDate="maxDate" @close="show = false" color="#FF8007">
		</u-calendar>


	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	const chooseLocation = requirePlugin('chooseLocation');
	// #endif

	// #ifdef APP
	import permision from "@/js_sdk/wa-permission/permission.js"
	// #endif

	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;



	const d = new Date()
	const year = d.getFullYear()
	let month = d.getMonth() + 1
	month = month < 10 ? `0${month}` : month
	const date = d.getDate()
	export default {
		data() {
			return {
				stop: true,
				select: false,
				unit: '次',
				locations: {
					address: '',
					province: '',
					city: '',
					district: '',
					latitude: '',
					longitude: '',
				},
				items: [],
				fileList1: [],
				name: '',
				username: '',
				mobile: '',
				num: '',
				// starttime: Number(new Date()),
				show: false,
				show1: false,
				file: '',
				cate: '',
				cate_id: '',
				content: '',
				time: '',
				price: '',
				info: '',
				maxDate: `${year}-${month}-${date+30}`,
				voicePath: ''
			};
		},

		mounted() {
			// #ifdef APP
			let that = this
			uni.$on('selectAddress', function(data) {
				console.log(data)
				that.locations.province = data.province
				that.locations.city = data.city
				that.locations.district = data.district
				that.locations.longitude = data.location.longitude
				that.locations.latitude = data.location.latitude
				that.locations.address = data.address + data.name
			})
			// #endif
		},
		onShow() {
			// #ifdef MP-WEIXIN
			const locations = chooseLocation.getLocation();
			if (locations) {
				this.locations = Object.assign(this.locations, locations)
			}
			// #endif
		},
		onLoad(option) {
			this.getType()


			let self = this;
			recorderManager.onStop(function(res) {
				console.log('recorder stop' + JSON.stringify(res));

				uni.uploadFile({
					url: self.Upload.uploadurl, // 仅为示例，非真实的接口地址
					filePath: res.tempFilePath,
					name: 'file',
					formData: {
						type: 'mp3'
					},
					success: (res) => {
						let data = JSON.parse(res.data)
						self.voicePath = data.data
					}
				});
			});

		},
		onUnload() {
			// #ifdef MP-WEIXIN
			// 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
			chooseLocation.setLocation(null);
			// #endif

		},

		methods: {
			playVoice() {
				console.log('播放录音');

				if (this.voicePath) {
					innerAudioContext.src = this.oss(this.voicePath);
					innerAudioContext.play();
				}
			},
			play() {
				let that = this
				// #ifdef MP-WEIXIN
				uni.authorize({
					scope: 'scope.record',
					success() {
						that.stop = !that.stop
						if (that.stop) {
							console.log('停止录音')
							uni.hideLoading();
							recorderManager.stop()
						} else {
							console.log('开始了录音')
							recorderManager.start()
						}
					}
				})
				// #endif
				// #ifdef APP
				that.stop = !that.stop
				if (that.stop) {
					console.log('停止录音')
					uni.hideLoading();
					recorderManager.stop()
				} else {
					console.log('开始了录音')
					recorderManager.start()
				}
				// #endif


			},
			confirm1(e) {
				this.show1 = false
				let that = this
				console.log(e)
				uni.uploadFile({
					url: that.Upload.uploadurl, // 仅为示例，非真实的接口地址
					filePath: e,
					name: 'file',
					formData: {
						type: 'mp3',
						token: uni.getStorageSync('token')
					},
					success: (res) => {
						let data = JSON.parse(res.data)
						that.file = data.data.url
					}
				});
			},
			confirm(e) {
				console.log(e)
				this.show = false
				this.time = e[0]
				this.starttime = e[0]
			},
			save() {
				// if (this.cate_id === '') {
				// 	uni.$u.toast('请选择分类');
				// 	return
				// }
				if (this.name === '') {
					uni.$u.toast('请输入任务标题');
					return
				}
				if (!uni.$u.test.digits(this.num)) {
					uni.$u.toast('请输入正确的人数');
					return
				}
				// if (!uni.$u.test.amount(this.price)) {
				// 	uni.$u.toast('请输入正确的金额');
				// 	return
				// }
				// if (this.time === '') {
				// 	uni.$u.toast('请选择上门时间');
				// 	return
				// }
				if (this.content === '') {
					uni.$u.toast('请输入任务内容');
					return
				}

				if (this.locations.address === '') {
					uni.$u.toast('请选择上门地址');
					return
				}
				// if (this.fileList1.length === 0) {
				// 	uni.$u.toast('请上传任务封面');
				// 	return
				// }
				if (!uni.$u.test.chinese(this.username)) {
					uni.$u.toast('请输入联系人');
					return
				}
				if (!uni.$u.test.mobile(this.mobile)) {
					uni.$u.toast('请输入正确的手机号');
					return
				}
				if (!this.select) {
					uni.$u.toast('请先同意《同城任务发布规则》');
					return
				}



				let images = this.fileList1.map((value) => {
					return value.url.url
				})
				console.log(this.starttime)
				uni.$u.http.post('/postcity ', {
					// cate_id: this.cate_id,
					name: this.name,
					username: this.username,
					mobile: this.mobile,
					num: this.num,
					price: this.price,
					total_price: this.price * this.num,
					// starttime: this.time,
					content: this.content,
					address: this.locations.address,
					city: this.locations.city,
					lng: this.locations.longitude,
					lat: this.locations.latitude,
					images: images.join(','),
					file: this.voicePath,
				}).then(res => {
					if (res.code == 1) {
						uni.$u.toast(res.msg)
						setTimeout(() => {
							uni.$u.route({
								type: 'back'
							})
						}, 1000)
					}
				}).catch((res) => {

				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					console.log(result)
					if (result) {
						let item = this[`fileList${event.name}`][fileListLen]
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
					} else {
						this[`fileList${event.name}`].splice(fileListLen, 1)
					}

				}
				console.log(this[`fileList${event.name}`])
			},
			uploadFilePromise(url) {
				console.log(url);
			
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.Upload.uploadurl, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							type: 'image',
							token: uni.getStorageSync('token')
						},
						success: (res) => {
							let data = JSON.parse(res.data)
							if (res.statusCode === 200 && data.code === 1 && data.data) {
								resolve(data.data)
							} else {
								resolve()
							}
						}
					});
				});
			},
			onchange(e) {
				console.log(e.detail)
				// const value = e.detail.value
				if (e.detail.value.length > 1) {
					console.log(111)
					this.cate_id = e.detail.value[1].value
					this.cate = e.detail.value[1].text
				} else {
					console.log(222)
					this.cate_id = e.detail.value[0].value
					this.cate = e.detail.value[0].text
				}

			},
			onnodeclick(node) {},
			getType() {
				uni.$u.http.post('/getcitycate ', {}).then(res => {
					if (res.code == 1) {
						this.items = res.data

					}
				}).catch((res) => {

				})
				uni.$u.http.post('/getconfig', {
					type: 11
				}).then(res => {
					if (res.code == 1) {
						res.data.config = res.data.config.replace(/<img/g,
							"<img style='max-width:100%;height:auto'")
						this.info = res.data.config

					}
				}).catch((res) => {

				})
			},
			map() {
				console.log(1111)
				uni.$u.route({
					url: 'pages/my/map'
				})
			},
			nearby() {
				// #ifdef MP-WEIXIN
				const key = 'LNWBZ-4DTKU-JQCVV-23LKL-4GM2V-2RBQI'; //使用在腾讯位置服务申请的key
				const referer = '跑腿'; //调用插件的app的名称
				let location;
				if (this.locations.latitude) {
					location = JSON.stringify({
						latitude: this.locations.latitude,
						longitude: this.locations.longitude
					});
				} else {
					location = ''
				}
				console.log(location)
				const category = '';

				wx.navigateTo({
					url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' +
						location + '&category=' + category
				});
				// #endif

				// #ifdef APP

				let allow = permision.checkSystemEnableLocation()
				if (allow) {
					uni.$u.route({
						url: 'pages/my/map'
					})
				} else {
					uni.showModal({
						title: '温馨提示',
						content: '请打开手机位置信息或点击下方确定开启APP权限中的位置信息',
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppPermissionSetting()
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}

				// #endif
			},
		}
	}
</script>
<style>
	.auth .input-value-border {
		opacity: 0;
	}
</style>
<style lang="scss" scoped>
	page {
		background: #F6F6F6;
	}

	.auth {
		background: linear-gradient(to bottom, #FFC141, #F6F6F6);
		background-size: 750rpx 500rpx;
		background-repeat: no-repeat;
		padding-top: 50rpx;

		.btn {
			background: linear-gradient(to right, #FFDF41, #FFC141);
			height: 88rpx;
			border: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 50rpx auto 50rpx;
			width: 590rpx;
			border-radius: 44rpx;
		}

		.agree {
			display: flex;
			align-items: center;
			padding: 30rpx 20rpx 20rpx;

			.circle {
				width: 30rpx;
				height: 30rpx;
				box-sizing: border-box;
				border-radius: 50%;
				border: 1px solid #999999;
				margin-right: 10rpx;
				display: flex;
				align-items: center;
			}

			.select {
				width: 22rpx;
				height: 22rpx;
			}

			.other {
				font-size: 22rpx;
				color: #999999;
			}

			.rule {
				font-size: 22rpx;
				color: #FF8007;
			}
		}

		.notice {
			font-size: 22rpx;
			color: #FF8007;
			padding: 0 20rpx;
		}

		.info {
			background: #FFFFFF;
			margin: 0 20rpx;
			border-radius: 20rpx;
			padding: 0 20rpx 20rpx;

			.line {
				height: 100rpx;
				display: flex;
				align-items: center;
				border-bottom: 1px solid #F6F6F6;
				position: relative;

				.l {
					color: #575859;
					font-size: 32rpx;
					width: 180rpx;
					text-align: right;
				}

				.r {
					flex: 1;
				}

				.picker {
					position: absolute;
					height: 100%;
					left: 180rpx;
					right: 0;
					top: 10rpx;
					z-index: 100;
				}

				.con {

					// height: 100%;
				}
			}

			.voice {
				padding: 20rpx;
				display: flex;
				align-items: center;
				position: relative;
				z-index: 10;

				.voicebtn {
					width: 114rpx;
					height: 114rpx;
					display: flex;
					align-items: center;
					flex-direction: column;
					justify-content: center;
					background: linear-gradient(to bottom, #95C0FF, #428DFC);
					margin-right: 40rpx;
					border-radius: 50%;

					.icon {
						width: 40rpx;
						height: 53rpx;
					}

					.word {
						font-size: 24rpx;
						color: #fff;
					}
				}

				.shape {
					flex: 1;
					position: relative;

					.close {
						position: absolute;
						right: 10rpx;
						top: 10rpx;
						width: 42rpx;
						height: 42rpx;
					}

					.icon {
						width: 408rpx;
						height: 105rpx;
					}
				}
			}

			.imgBox {
				height: auto;
				align-items: flex-start;
				padding: 20rpx 0;
				justify-content: flex-start;
				position: relative;

				.address {
					position: absolute;
					width: 30rpx;
					height: 40rpx;
					right: 30rpx;
					bottom: 30rpx;
					z-index: 2;
				}
			}

			.box {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				height: 170rpx;
				width: 170rpx;
				border: 1px solid #FFCE54;
				border-radius: 20rpx;

				.icon {
					width: 51rpx;
					height: 49rpx;
				}

				.word {
					color: #FF8007;
					font-size: 30rpx;
					margin-top: 20rpx;
				}
			}
		}
	}
</style>
